import { request } from "./index"
import nprogress from "nprogress"
import "nprogress/nprogress.css"
import store from "@/store"

//请求拦截器
request.interceptors.request.use((config) => {
  nprogress.start()
  //获取用户临时身份信息的值,然后随着header的[userTempId]字段发送
  let userTempId = store.state.user.userTempId
  config.headers.userTempId = userTempId
  //如果用户登录了,我们需要在header中携带token(用来请求后端数据时进行鉴权操作)
  const token = store.state.user.token
  config.headers.token = token
  return config
})

//响应拦截器
request.interceptors.response.use(
  (response) => {
    nprogress.done()
    // console.log(response.data)
    if (response.data.code === 200) {
      return response.data.data
    } else {
      return Promise.reject({ message: response.data.message })
    }
  },
  (error) => {
    nprogress.done()

    return Promise.reject(error)
  }
)
export default request
